package com.wangzefeng.shop.security.service.impl;

import com.wangzefeng.shop.entity.SysRole;
import com.wangzefeng.shop.entity.SysUser;
import com.wangzefeng.shop.mapper.SysRoleMapper;
import com.wangzefeng.shop.mapper.SysUserMapper;
import com.wangzefeng.shop.security.vo.AuthUser;
import com.wangzefeng.shop.security.vo.GrantedAuthorityImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wangzefeng
 * @Date: 2021/3/18 14:13
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectOneByUsername(s);
        AuthUser authUser=new AuthUser();
        if(sysUser==null){
            throw new UsernameNotFoundException("登陆失败，用户名错误或用户名不存在");
        }
        BeanUtils.copyProperties(sysUser,authUser);
        if(authUser.getUserStatus()==-1){
            throw new UsernameNotFoundException("登陆失败，该用户账号已被冻结");
        }
        List<SysRole> sysRoles = sysRoleMapper.selectRolesByUserId(authUser.getUserId());
        List<GrantedAuthority> authorities =new ArrayList<>();
        for (SysRole role : sysRoles) {
            authorities.add(new GrantedAuthorityImpl(role.getRoleId()+""));
        }
        authUser.setAuthorities(authorities);
        return authUser;
    }
}
